package offer;

public class Solution13 {
    int m, n;
    boolean[][] v;

    public int movingCount(int m, int n, int k) {
        this.m = m;
        this.n = n;
        v = new boolean[m][n];
        return dfs(0, 0, k);
    }

    private int dfs(int i, int j, int k) {
        if (i < 0 || j < 0 || i >= m || j >= n) {
            return 0;
        }
        if (v[i][j]) {
            return 0;
        }
        v[i][j] = true;
        int sum = sumOfDigit(i) + sumOfDigit(j);
        if (sum > k) {
            return 0;
        }
        return dfs(i - 1, j, k) + dfs(i, j - 1, k) + dfs(i + 1, j, k) + dfs(i, j + 1, k) + 1;
    }

    private int sumOfDigit(int num) {
        int res = 0;
        while (num != 0) {
            res += num % 10;
            num /= 10;
        }
        return res;
    }
}
